/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2007 University of Washington
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "ns3/log.h"
#include "ns3/enum.h"
#include "ns3/uinteger.h"
#include "ns3/node.h"
#include "ns3/ppp-header.h"
#include "texcp-queue.h"
#include "texcp-header.h"
#include "ns3/udp-header.h"
#include "ns3/ipv4-header.h"
#include "ns3/trace-source-accessor.h"

/********** Constants ***********/
/// Constant alpha for the load balancer
#define ALPHA 0.4

/// Beta 
#define BETA 0.225

NS_LOG_COMPONENT_DEFINE ("TexcpQueue");

namespace ns3 {

namespace texcp_routing {

NS_OBJECT_ENSURE_REGISTERED (TexcpQueue);

int TexcpQueue::m_nbrQueues = 0;
TypeId TexcpQueue::GetTypeId (void) 
{
  static TypeId tid = TypeId ("ns3::texcp_routing::TexcpQueue")
    .SetParent<Queue> ()
    .AddConstructor<TexcpQueue> ()
    .AddAttribute ("Mode", 
                   "Whether to use Bytes (see MaxBytes) or Packets (see MaxPackets) as the maximum queue size metric.",
                   EnumValue (BYTES),
                   MakeEnumAccessor (&TexcpQueue::SetMode),
                   MakeEnumChecker (BYTES, "Bytes",
                                    PACKETS, "Packets"))
    .AddAttribute ("MaxPackets", 
                   "The maximum number of packets accepted by this TexcpQueue.",
                   UintegerValue (100),
                   MakeUintegerAccessor (&TexcpQueue::m_maxPackets),
                   MakeUintegerChecker<uint32_t> ())
    .AddAttribute ("MaxBytes", 
                   "The maximum number of bytes accepted by this TexcpQueue.",
                   UintegerValue (62500),
                   MakeUintegerAccessor (&TexcpQueue::m_maxBytes),
                   MakeUintegerChecker<uint32_t> ())
    .AddAttribute ("DataRate", 
                   "Link data rate needed for computing texcp probe",
                   DataRateValue (DataRate("0Mbps")),
                   MakeDataRateAccessor (&TexcpQueue::m_bps),
                   MakeDataRateChecker())
    .AddAttribute ("ProbeEstimatedInterval", 
                   "An estimation of the interval between probes used for internal statistics update",
                   TimeValue (Seconds(0.1)),
                   MakeTimeAccessor (&TexcpQueue::m_probeInt),
                   MakeTimeChecker())
    .AddTraceSource ("LinkUtilization", 
                  "Fraction of time the link is utilized",
                   MakeTraceSourceAccessor (&TexcpQueue::m_pathUtilization))
    .AddTraceSource ("LinkDroppingRate", 
                  "Ratio of dropped bytes over total Received bytes",
                   MakeTraceSourceAccessor (&TexcpQueue::m_loss))


    ;
  
  return tid;
}

TexcpQueue::TexcpQueue () :
  Queue (),
  m_packets (),
  m_bytesInQueue (0),
  m_iePairsTimer (Timer::CANCEL_ON_DESTROY),
  m_texcpUpdateTimer (Timer::CANCEL_ON_DESTROY)
{
  NS_LOG_FUNCTION_NOARGS ();
  DoStart();
  m_probeInt = Seconds(0.1);
  m_nbrIEPairs = 1;

}

TexcpQueue::TexcpQueue (std::string rate) :
  Queue (),
  m_packets (),
  m_bytesInQueue (0),
  m_iePairsTimer (Timer::CANCEL_ON_DESTROY),
  m_texcpUpdateTimer(Timer::CANCEL_ON_DESTROY)
{
  NS_LOG_FUNCTION_NOARGS ();
  m_bps = DataRate(rate);
}
TexcpQueue::~TexcpQueue ()
{
  NS_LOG_FUNCTION_NOARGS ();
  ascii.close();
}

  void 
TexcpQueue::SetMode (enum Mode mode)
{
  NS_LOG_FUNCTION (mode);
  m_mode = mode;
}

 TexcpQueue::Mode
TexcpQueue::GetMode (void)
{
  NS_LOG_FUNCTION_NOARGS ();
  return m_mode;
}

void
TexcpQueue::ResetStatistics()
{
  NS_LOG_FUNCTION_NOARGS ();
  Queue::ResetStatistics();
}
 
void
TexcpQueue::DoStart()
{
  NS_LOG_FUNCTION_NOARGS ();
 NS_LOG_INFO("Queue :: Do Start");
 id = TexcpQueue::Next();
 m_iePairsTimer.SetFunction(&TexcpQueue::IEPairsTimerExpire, this);
 m_iePairsTimer.Schedule(Seconds(3*m_probeInt.GetSeconds()));
 m_texcpUpdateTimer.SetFunction(&TexcpQueue::TexcpUpdateTimerExpire, this);
 m_texcpUpdateTimer.Schedule(Seconds(0.5*m_probeInt.GetSeconds()));
}
bool 
TexcpQueue::DoEnqueue (Ptr<Packet> p)
{
  //NS_LOG_INFO("Enqueue");
  NS_LOG_FUNCTION (this << p);
  if (m_mode == PACKETS && (m_packets.size () >= m_maxPackets))
    {
      NS_LOG_LOGIC ("Queue full (at max packets) -- droppping pkt");
      Drop (p);
      return false;
    }

  if (m_mode == BYTES && (m_bytesInQueue + p->GetSize () >= m_maxBytes))
    {
      NS_LOG_LOGIC ("Queue full (packet would exceed max bytes) -- droppping pkt");
      Drop (p);
      return false;
    }
  //NS_LOG_INFO("DoEnqueue");
  TexcpTag tag;
  if (p->PeekPacketTag(tag))
    {
      PppHeader pppHeader;
      Ipv4Header ipHeader;
      UdpHeader udpHeader;
      TexcpHeader tHeader;
      p->RemoveHeader(pppHeader);
      p->RemoveHeader(ipHeader);
      p->RemoveHeader(udpHeader);
      p->RemoveHeader(tHeader);
      
      //NS_LOG_INFO("queue Probe recieved" << m_aggregateFeedback);
      //See if the probe is from a new IE pair
      struct IEPair ie = {ipHeader.GetSource(), ipHeader.GetDestination()};
      if (!IsExistingIEPair(ie)) m_observedIEPairs.push_back(ie);
      
      //Modify the probe with the current router information
      tHeader = SetProbe(tHeader); 
      
      //if(ascii.is_open()) NS_LOG_INFO("Id " << id <<  " Interface " << tHeader.GetInterfaceIdx() << " " << m_pathUtilization);
      //Putting bacj the headers
      p->AddHeader(tHeader);
      p->AddHeader(udpHeader);
      p->AddHeader(ipHeader);
      p->AddHeader(pppHeader); 
    } 

  m_bytesInQueue += p->GetSize ();
  m_packets.push(p);

  NS_LOG_LOGIC ("Number packets " << m_packets.size ());
  NS_LOG_LOGIC ("Number bytes " << m_bytesInQueue);

  return true;
}

Ptr<Packet>
TexcpQueue::DoDequeue (void)
{
  NS_LOG_FUNCTION (this);

  if (m_packets.empty()) 
    {
      NS_LOG_LOGIC ("Queue empty");
      return 0;
    }

  Ptr<Packet> p = m_packets.front ();
  m_packets.pop ();
  m_bytesInQueue -= p->GetSize ();

  NS_LOG_LOGIC ("Popped " << p);

  NS_LOG_LOGIC ("Number packets " << m_packets.size ());
  NS_LOG_LOGIC ("Number bytes " << m_bytesInQueue);

  return p;
}

Ptr<const Packet>
TexcpQueue::DoPeek (void) const
{
  NS_LOG_FUNCTION (this);

  if (m_packets.empty()) 
    {
      NS_LOG_LOGIC ("Queue empty");
      return 0;
    }

  Ptr<Packet> p = m_packets.front ();

  NS_LOG_LOGIC ("Number packets " << m_packets.size ());
  NS_LOG_LOGIC ("Number bytes " << m_bytesInQueue);

  return p;
}

TexcpHeader
TexcpQueue::SetProbe(TexcpHeader probe)
{
  NS_LOG_FUNCTION_NOARGS ();
  double pathUtilization = m_pathUtilization;
  double positiveFeedback = 0;
  double negativeFeedback = 0;
  //NS_LOG_INFO(" AggregateFeedback " <<m_aggregateFeedback);
  if (m_aggregateFeedback < 0)
    {
      positiveFeedback = 0;
      if (pathUtilization != 0)
        {
          negativeFeedback = (-m_aggregateFeedback)/(pathUtilization * m_bps.GetBitRate());
        }
      else 
        {
          negativeFeedback = 0;
        }

    } 
  else 
    {
      negativeFeedback = 0;
      if (m_nbrIEPairs != 0)
        {
          positiveFeedback = m_aggregateFeedback/m_nbrIEPairs;
        }
      else 
        {
          positiveFeedback = 0;
        }
    }

  if(probe.GetPathUtilization() < pathUtilization) probe.SetPathUtilization(pathUtilization);
  if(probe.GetPositiveFeedback() > positiveFeedback) probe.SetPositiveFeedback(positiveFeedback);
  if(probe.GetNegativeFeedback() < negativeFeedback) probe.SetNegativeFeedback(negativeFeedback);
  probe.SetPathLoss(m_loss + probe.GetPathLoss());
  //std::cout << m_loss << '\n';
  return probe;
}

void
TexcpQueue::IEPairsTimerExpire ()
{
 NS_LOG_FUNCTION_NOARGS ();
 m_nbrIEPairs = m_observedIEPairs.size();
 m_observedIEPairs.clear();
 //NS_LOG_INFO("Id " << id << " " << m_pathUtilization);
 //NS_LOG_INFO("Number of observed IE pairs "<<m_nbrIEPairs);
 m_iePairsTimer.Schedule(Seconds(3*m_probeInt.GetSeconds()));
}

void
TexcpQueue::TexcpUpdateTimerExpire ()
{   
 NS_LOG_FUNCTION_NOARGS ();

 Time upInt = Seconds(1.0*m_probeInt.GetSeconds());

 uint32_t droppedBytes =  GetTotalDroppedBytes();
 uint32_t bytesInQueue = GetNBytes();
 uint32_t receivedBytes = GetTotalReceivedBytes();
 ResetStatistics();
 //double pathUtilization = 8.0*receivedBytes;
 double pathUtilization = 8.0*(m_bytesPrevInQueue  + receivedBytes - droppedBytes-bytesInQueue);
 pathUtilization/=(static_cast<double>( m_bps.GetBitRate())*upInt.GetSeconds());
 

 if (pathUtilization > 1) pathUtilization = 1.0;
 NS_LOG_INFO("Queue Prev" << m_bytesPrevInQueue << " Now " << bytesInQueue << " Recv " << receivedBytes << " Drop " << droppedBytes << " bitRate " << m_bps);
 m_bytesPrevInQueue =  bytesInQueue;
 double oldPathUtil = m_pathUtilization;
 double newPathUtil = 0.0;
 newPathUtil = 0.9*oldPathUtil + 0.1*pathUtilization;
 m_pathUtilization = newPathUtil;
 NS_LOG_INFO("Old path Utilizatio " << oldPathUtil << "new path Util " << pathUtilization << " EMAver " << m_pathUtilization );
 
 double load = 8.0*(receivedBytes);
 load /=(upInt.GetSeconds()); 
 //m_aggregateFeedback = ALPHA*m_probeInt.GetSeconds()*(1-pathUtilization)*m_bps.GetBitRate() - BETA * bytesInQueue * 8.0;
 m_aggregateFeedback = ALPHA*m_probeInt.GetSeconds()*(m_bps.GetBitRate()-load) - BETA * bytesInQueue * 8.0;
 //std::cout << "load " << load << " aggregateFeedback " << m_aggregateFeedback << "\n";

 //Old tracing to be deleted
 if (ascii.is_open()) TxPathUtilization (m_pathUtilization);

 //Loss rate not in use
 double lossRate = 0.0;
 if (receivedBytes) 
   {
    lossRate = (double)droppedBytes;
    lossRate /= (double)receivedBytes;
   }
 //std::cout << lossRate << " lossRate\n";
 double oldLoss = m_loss; 
 //std::cout << oldLoss << " old m_loss\n";
 m_loss = 0.95*oldLoss+0.05*lossRate;
 
 //std::cout << m_loss << " new m_loss\n";
 m_texcpUpdateTimer.Schedule(upInt);
}

bool
TexcpQueue::IsExistingIEPair(IEPair ir)
{
 NS_LOG_FUNCTION_NOARGS ();
  for(std::list<IEPair>::iterator i = m_observedIEPairs.begin();
      i != m_observedIEPairs.end(); i++)
     {
       if( ir == (*i)) return true;
     }
  return false;
}

void
TexcpQueue::SetOutput (std::string filename)
{
 NS_LOG_FUNCTION_NOARGS ();
  ascii.open(filename.c_str());
 //NS_LOG_INFO("Queue SetOutput " << id << " " << ascii.is_open());
}

void 
TexcpQueue::TxPathUtilization (double u)
{
  //NS_LOG_INFO("Tx " << id);
  ascii << Simulator::Now().GetTimeStep() <<  " " << u <<"\n";
}
}} // namespace ns3, texcp_routing


